/////////////////////////////////////////////////////////////////////////////
//
// XepdtLogConsole.cpp
//
//
/////////////////////////////////////////////////////////////////////////////

#include "StdAfx.h"
#include "XepdtLogConsole.h"


/////////////////////////////////////////////////////////////////////////////
// CXepdtLogConsole


CXepdtLogConsole::CXepdtLogConsole()
{
#ifdef _DEBUG
	m_bInit = FALSE;

	m_nIndex  = 0;
	m_hStdOUt = NULL;
#endif // _DEBUG
}

CXepdtLogConsole::~CXepdtLogConsole()
{
#ifdef _DEBUG
	FreeConsole();
#endif // _DEBUG
}


/////////////////////////////////////////////////////////////////////////////
// CXepdtLogConsole method implementation

BOOL CXepdtLogConsole::Init()
{
#ifdef _DEBUG

	OSVERSIONINFO osVer;
	osVer.dwOSVersionInfoSize = sizeof( osVer );
	GetVersionEx( & osVer );

	if ( osVer.dwPlatformId == VER_PLATFORM_WIN32s )
	{
		m_bInit = FALSE;
		return FALSE;
	}

	if (AllocConsole())
	{
		SetConsoleTitleA( "Xepdt" );
		m_hStdOUt = GetStdHandle( STD_OUTPUT_HANDLE );
		ASSERT( m_hStdOUt );
	}
	else
	{
		m_hStdOUt = GetStdHandle( STD_OUTPUT_HANDLE );
		if (m_hStdOUt)
		{
			SetConsoleTitleA( "Xepdt" );
		}
		else
		{
			m_bInit = FALSE;
			return FALSE;
		}
	}

	m_bInit = TRUE;

#endif // _DEBUG

	return TRUE;
}

VOID CXepdtLogConsole::OutputXepdtInfo( std::string strInfo, TEXT_COLOR textColor )
{
#ifdef _DEBUG
	if ( ! m_bInit )
		return;

	// CleanConsoleScreen();

	m_nIndex++;

	char buffer[10240 * 2];
	sprintf_s(buffer,10240 * 2, "<%05d> %s \n\n", m_nIndex, strInfo.c_str() );
	std::string strOutputInfo(buffer);

	DWORD dwCount;

	ASSERT( m_hStdOUt );
	SetConsoleTextAttribute( m_hStdOUt, textColor );
	WriteConsole( m_hStdOUt, strOutputInfo.c_str(), strOutputInfo.length(), & dwCount, NULL );

	/////////////////////////////////////////////////////////////////////////
	// static std::string log;
	// log += strOutputInfo.operator LPCTSTR();
	// log += "\n";
	
	// CStdioFile file;
	// if ( ! file.Open( "C:\\XepdtLog.txt", CFile::modeCreate | CFile::modeWrite ) )
	// 	return;
	
	// file.WriteString( log.c_str() );
	// file.Close();
	/////////////////////////////////////////////////////////////////////////
#endif // _DEBUG
}

VOID CXepdtLogConsole::CleanConsoleScreen()
{
#ifdef _DEBUG
	if ( ! m_bInit )
		return;

	ASSERT( m_hStdOUt );

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo( m_hStdOUt, & csbi );

	DWORD dwConSize   = csbi.dwSize.X * csbi.dwSize.Y;
	DWORD dwWritten   = 0;

	COORD coordScreen = { 0, 0 };

	FillConsoleOutputCharacter( m_hStdOUt, ( TCHAR ) ' ', dwConSize, coordScreen, & dwWritten );

	GetConsoleScreenBufferInfo( m_hStdOUt, & csbi );
	FillConsoleOutputAttribute( m_hStdOUt, csbi.wAttributes, dwConSize, coordScreen, & dwWritten );
	SetConsoleCursorPosition( m_hStdOUt, coordScreen );
#endif // _DEBUG
}